
<template>
  <div>
    <div class="gva-search-box">
      <el-form
        ref="elSearchFormRef"
        :inline="true"
        :model="searchInfo"
        class="demo-form-inline"
        :rules="searchRule"
        @keyup.enter="onSubmit"
      >
        <el-form-item
          label="创建日期"
          prop="createdAt"
        >
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker
            v-model="searchInfo.startCreatedAt"
            type="datetime"
            placeholder="开始日期"
            :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"
          />
          —
          <el-date-picker
            v-model="searchInfo.endCreatedAt"
            type="datetime"
            placeholder="结束日期"
            :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"
          />
        </el-form-item>
        <el-form-item
          label="邀请人手机号"
          prop="inviteUserId"
        >
          <el-input
            v-model="searchInfo.inviteUserPhone"
            placeholder="搜索条件"
          />
        </el-form-item>
        <el-form-item
          label="用户手机号"
          prop="phone"
        >
          <el-input
            v-model="searchInfo.phone"
            placeholder="搜索条件"
          />
        </el-form-item>
        <el-form-item
          label="名称"
          prop="name"
        >
          <el-input
            v-model="searchInfo.name"
            placeholder="搜索条件"
          />

        </el-form-item>
        <el-form-item
          label="用户类型"
          prop="types"
        >
          <el-select
            v-model="searchInfo.types"
            clearable
          >
            <el-option
              v-for="(option,key) in typeOption"
              :key="key"
              :label="option"
              :value="key"
            />

          </el-select>

        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="search"
            @click="onSubmit"
          >查询</el-button>
          <el-button
            icon="refresh"
            @click="onReset"
          >重置</el-button>
<!--          <el-button-->
<!--            icon="download"-->
<!--            @click="exportUserExcel"-->
<!--          >导出</el-button>-->

        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
      >
        <el-table-column
          align="center"
          label="报告生成日期"
          width="180"
        >
          <template #default="scope">{{ formatDateYmd(scope.row.reportTime) }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          label="用户手机号"
          prop="phone"
          width="120"
        />
        <el-table-column
          align="center"
          label="名称"
          prop="name"
          width="120"
        />
        <el-table-column
          align="center"
          label="性别"
          prop="sex"
          width="120"
        >
          <template #default="{row}">
            {{ row.sex == '1'?'男':'女' }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="生日"
          width="180"
        >
          <template #default="scope">{{ formatDateYmd(scope.row.birthday) }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          label="用户体质"
          width="120"
        >
          <template #default="{row}">
            {{ physiqueMap[row.physique] }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="用户类型"
          prop="types"
          width="120"
        >
          <template #default="{row}">
            {{ typeOption[row.types] }}
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="操作"
          min-width="120"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              class="table-button"
              @click="getReport(scope.row,'naobo')"
            >
              脑波方案
            </el-button>
            <el-button
              type="primary"
              link
              class="table-button"
              @click="getReport(scope.row,'yundong')"
            >
              运动方案
            </el-button>
            <el-button
              type="primary"
              link
              class="table-button"
              @click="getReport(scope.row,'yinshi')"
            >
              饮食方案
            </el-button>
            <el-button
              type="primary"
              link
              class="table-button"
              @click="getReport(scope.row,'ganyu')"
            >
              干预方案
            </el-button>
            
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogMap.naobo"
      title="脑波方案"
    >
      <el-checkbox-group v-model="ids">
        <div class="border rounded border-solid border-gray-200 p-4 grid grid-cols-3 gap-4">
          <el-checkbox
            v-for="option in naoboOption"
            :key="option.key"
            class="truncate"
            border
            :label="option.key"
          >
            <el-tooltip
              :content="option.value"
            >
              {{ option.value }}
            </el-tooltip>
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="setReport"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogMap.yundong"
      title="运动方案"
    >
      <el-checkbox-group v-model="ids">
        <div class="border rounded border-solid border-gray-200 p-4 grid grid-cols-3 gap-4">
          <el-checkbox
            v-for="option in yundongOption"
            :key="option.key"
            class="truncate"
            border
            :label="option.key"
          >
            <el-tooltip
              :content="option.value"
            >
              {{ option.value }}
            </el-tooltip>
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="setReport"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogMap.yinshi"
      title="饮食方案"
    >
      <el-checkbox-group v-model="ids">
        <div class="border rounded border-solid border-gray-200 p-4 grid grid-cols-3 gap-4">
          <el-checkbox
            v-for="option in yinshiOption"
            :key="option.key"
            class="truncate"
            border
            :label="option.key"
          >
            <el-tooltip
              :content="option.value"
            >
              {{ option.value }}
            </el-tooltip>
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="setReport"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogMap.ganyu"
      title="干预方案"
    >
      <el-form label-width="80px">
        <el-form-item label="干预方案">
          <rich-edit v-model="content" />
        </el-form-item>
        <el-form-item label="金额">
          <el-input
            v-model.number="money"
            placeholder="请输入金额"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="setReport"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<script setup>
import {
  getArticle,
  getUserList, getUserRecord, setUserRecord, excelUserList
} from '@/api/fdUser'

// 全量引入格式化工具 请按需保留
import { formatDate, formatBoolean, formatDateYmd } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { getPhysiqueList } from '@/api/physique'
import RichEdit from '@/components/richtext/rich-edit.vue'
import { useRoute } from 'vue-router'

defineOptions({
  name: 'FdUser'
})

const activeID = ref(0)
const ids = ref([])
const money = ref(0)
const content = ref('')
const flag = ref('')

const route = useRoute()

const dialogMap = reactive({
  naobo: false,
  yundong: false,
  yinshi: false,
  ganyu: false,
})

const naoboOption = ref([])
const yundongOption = ref([])
const yinshiOption = ref([])

const closeDialog = () => {
  dialogMap[flag.value] = false
  ids.value = []
}

const exportUserExcel = () => {
  const queryInfo = {
    ...searchInfo.value,
  }
  if (!queryInfo.startCreatedAt) {
    delete queryInfo.startCreatedAt
  }
  if (!queryInfo.endCreatedAt) {
    delete queryInfo.endCreatedAt
  }
  if (!queryInfo.grade) {
    delete queryInfo.grade
  }

  const params = Object.keys(queryInfo).map(key => `${key}=${queryInfo[key]}`).join('&')
  const url = import.meta.env.VITE_BASE_API + '/disease/excelUserList?' + params
  window.open(url, '_blank')
}

const getOptions = () => {
  getArticle().then(res => {
    if (res.code === 0) {
      naoboOption.value = res.data.naobo
      yundongOption.value = res.data.yundong
      yinshiOption.value = res.data.yinshi
    }
  })
}

getOptions()

const getReport = async(row, type) => {
  const res = await getUserRecord({ userID: row.ID, flag: type })
  if (res.code === 0) {
    if (res.data.ids) {
      ids.value = JSON.parse(res.data.ids)
    }
    content.value = res.data.content
    money.value = res.data.money
    activeID.value = res.data.ID
    dialogMap[type] = true
    flag.value = type
  }
}


const setReport = async() => {
  const res = await setUserRecord({ ID: activeID.value, ids: JSON.stringify(ids.value), content: content.value, money: money.value }, { flag: flag.value })
  if (res.code === 0) {
    ElMessage.success('设置成功')
    closeDialog()
  }
}

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const typeOption = ref({
  1: '普通用户',
  2: '会员',
  3: '过期用户',
})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    if (searchInfo.value.grade === '') {
      searchInfo.value.grade = null
    }
    if (searchInfo.value.types === '') {
      searchInfo.value.types = null
    }
    getTableData()
  })
}

const exportExcel = () => {

}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const users = route.query.users
  const table = await getUserList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value, users: users })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

const physiqueMap = ref({})
// 查询
const getPhysiqueListFunc = async() => {
  const res = await getPhysiqueList({ page: page.value, pageSize: 10000 })
  if (res.code === 0) {
    res.data.list.forEach(item => {
      physiqueMap.value[item.id] = item.tz_name
    })
  }
}
getPhysiqueListFunc()

</script>

<style>

</style>

